package com.qiangshi.web.controller.tasks;

import com.qiangshi.common.annotation.Log;
import com.qiangshi.common.core.controller.BaseController;
import com.qiangshi.common.core.domain.AjaxResult;
import com.qiangshi.common.core.domain.entity.SysUser;
import com.qiangshi.common.core.domain.model.LoginUser;
import com.qiangshi.common.core.page.TableDataInfo;
import com.qiangshi.common.enums.BusinessType;
import com.qiangshi.common.utils.DateUtils;
import com.qiangshi.common.utils.ServletUtils;
import com.qiangshi.common.utils.poi.ExcelUtil;
import com.qiangshi.framework.web.service.TokenService;
import com.qiangshi.system.service.ISysUserService;
import com.qiangshi.tasks.domain.QsProjectTasks;
import com.qiangshi.tasks.service.IQsProjectTasksService;
import com.qiangshi.tasksProgress.domain.QsTasksProgress;
import com.qiangshi.tasksProgress.service.IQsTasksProgressService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 项目任务Controller
 *
 * @author qiangshi
 * @date 2022-02-12
 */
@RestController
@RequestMapping("/tasks/tasks")
public class QsProjectTasksController extends BaseController {
    @Autowired
    private IQsProjectTasksService qsProjectTasksService;
    @Autowired
    private IQsTasksProgressService qsTasksProgressService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询项目任务列表
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:list')")
    @GetMapping("/list")
    public TableDataInfo list(QsProjectTasks qsProjectTasks) {
        startPage();
        List<QsProjectTasks> list = qsProjectTasksService.selectQsProjectTasksList(qsProjectTasks);
        List<SysUser> sysUserList = sysUserService.selectUserList(new SysUser());
        Map<Long, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.groupingBy(SysUser::getUserId, Collectors.collectingAndThen(toList(), value -> value.get(0))));
        for (QsProjectTasks projectTasks : list) {
            if (sysUserMap.containsKey(projectTasks.getPublisherId())) {
                projectTasks.setPublisherName(sysUserMap.get(projectTasks.getPublisherId()).getUserName());
            }
            if (sysUserMap.containsKey(projectTasks.getClaimerId())) {
                projectTasks.setClaimerName(sysUserMap.get(projectTasks.getClaimerId()).getUserName());
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询项目任务列表
     */
    @GetMapping("/getAppList")
    public AjaxResult getAppList(QsProjectTasks qsProjectTasks) {
        List<QsProjectTasks> list = qsProjectTasksService.selectQsProjectTasksList(qsProjectTasks);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        qsProjectTasks.setTasksType(0);
        SysUser user = loginUser.getUser();
        list = list.stream().filter(x -> !x.getTasksType().equals(0) || x.getPublisherId().equals(user.getUserId())).collect(toList());
        return AjaxResult.success(list);
    }

    /**
     * 导出项目任务列表
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:export')")
    @Log(title = "项目任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(QsProjectTasks qsProjectTasks) {
        List<QsProjectTasks> list = qsProjectTasksService.selectQsProjectTasksList(qsProjectTasks);
        ExcelUtil<QsProjectTasks> util = new ExcelUtil<QsProjectTasks>(QsProjectTasks.class);
        return util.exportExcel(list, "tasks");
    }

    /**
     * 获取项目任务详细信息
     */
    @PostMapping(value = "getAppDetail")
    public AjaxResult getAppDetail(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks = qsProjectTasksService.selectQsProjectTasksById(qsProjectTasks.getId());
        SysUser publisherUser = sysUserService.selectUserById(qsProjectTasks.getPublisherId());
        qsProjectTasks.setPublisherName(publisherUser.getNickName());
        if (Objects.nonNull(qsProjectTasks.getClaimerId())) {
            SysUser claimerIdUser = sysUserService.selectUserById(qsProjectTasks.getClaimerId());
            qsProjectTasks.setClaimerName(claimerIdUser.getNickName());
        }
        QsTasksProgress qsTasksProgress = new QsTasksProgress();
        qsTasksProgress.setTasksId(qsProjectTasks.getId());
        List<QsTasksProgress> tasksProgressList = qsTasksProgressService.selectQsTasksProgressList(qsTasksProgress);
        tasksProgressList = tasksProgressList.stream().sorted(Comparator.comparing(QsTasksProgress::getProgressNum).reversed()).collect(toList());
        if (CollectionUtils.isNotEmpty(tasksProgressList)) {
            qsProjectTasks.setProgressNum(tasksProgressList.get(0).getProgressNum());
        }
        return AjaxResult.success(qsProjectTasks);
    }

    /**
     * 判断发布人是不是当前登录人
     */
    @PostMapping(value = "checkPublisherId")
    public AjaxResult checkPublisherId(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks = qsProjectTasksService.selectQsProjectTasksById(qsProjectTasks.getId());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        if (qsProjectTasks.getPublisherId().equals(user.getUserId()) && !qsProjectTasks.getTasksType().equals(3)) {
            return AjaxResult.success(true);
        } else {
            return AjaxResult.success(false);
        }
    }

    /**
     * 判断认领人是不是当前登录人
     */
    @PostMapping(value = "checkClaimerId")
    public AjaxResult checkClaimerId(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks = qsProjectTasksService.selectQsProjectTasksById(qsProjectTasks.getId());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        if (Objects.nonNull(qsProjectTasks.getClaimerId())&&qsProjectTasks.getClaimerId().equals(user.getUserId()) && !qsProjectTasks.getTasksType().equals(3)) {
            return AjaxResult.success(true);
        } else {
            return AjaxResult.success(false);
        }
    }

    /**
     * 获取项目任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(qsProjectTasksService.selectQsProjectTasksById(id));
    }

    /**
     * 新增项目任务
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:add')")
    @Log(title = "项目任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks.setTasksNum("QST" + DateUtils.dateTimeNow());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        qsProjectTasks.setTasksType(0);
        SysUser user = loginUser.getUser();
        qsProjectTasks.setPublisherId(user.getUserId());
        return toAjax(qsProjectTasksService.insertQsProjectTasks(qsProjectTasks));
    }

    /**
     * app新增项目任务
     */
    @Log(title = "项目任务", businessType = BusinessType.INSERT)
    @PostMapping("addAppTasks")
    public AjaxResult addAppTasks(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks.setTasksNum("QST" + DateUtils.dateTimeNow());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        qsProjectTasks.setTasksType(0);
        SysUser user = loginUser.getUser();
        qsProjectTasks.setPublisherId(user.getUserId());
        qsProjectTasksService.insertQsProjectTasks(qsProjectTasks);
        return AjaxResult.success(qsProjectTasks);
    }

    /**
     * 修改项目任务
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:edit')")
    @Log(title = "项目任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QsProjectTasks qsProjectTasks) {
        return toAjax(qsProjectTasksService.updateQsProjectTasks(qsProjectTasks));
    }

    /**
     * 修改项目任务
     */
    @Log(title = "项目任务", businessType = BusinessType.UPDATE)
    @PostMapping("updateAppTasks")
    public AjaxResult updateAppTasks(@RequestBody QsProjectTasks qsProjectTasks) {
        QsProjectTasks qsProjectTasks1 = qsProjectTasksService.selectQsProjectTasksById(qsProjectTasks.getId());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        if (!qsProjectTasks1.getPublisherId().equals(user.getUserId())) {
            return AjaxResult.error();
        }
        return toAjax(qsProjectTasksService.updateQsProjectTasks(qsProjectTasks));
    }

    /**
     * 删除项目任务
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:remove')")
    @Log(title = "项目任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(qsProjectTasksService.deleteQsProjectTasksByIds(ids));
    }

    /**
     * 认领项目任务
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:claim')")
    @Log(title = "项目任务", businessType = BusinessType.CLAIM)
    @GetMapping("claim/{id}")
    public AjaxResult claim(@PathVariable Long id) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        return toAjax(qsProjectTasksService.claimQsProjectTasks(id, user.getUserId()));
    }

    /**
     * 发布项目任务
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:add')")
    @Log(title = "项目任务", businessType = BusinessType.INSERT)
    @GetMapping("release/{id}")
    public AjaxResult release(@PathVariable Long id) {
        QsProjectTasks qsProjectTasks = new QsProjectTasks();
        qsProjectTasks.setId(id);
        qsProjectTasks.setTasksType(1);
        qsProjectTasks.setReleaseTime(DateUtils.getNowDate());
        return toAjax(qsProjectTasksService.updateQsProjectTasks(qsProjectTasks));
    }

    /**
     * 发布项目任务
     */
    @Log(title = "项目任务", businessType = BusinessType.INSERT)
    @PostMapping("releaseAppTasks")
    public AjaxResult releaseAppTasks(@RequestBody QsProjectTasks qsProjectTasks) {
        qsProjectTasks.setTasksType(1);
        qsProjectTasks.setReleaseTime(DateUtils.getNowDate());
        return toAjax(qsProjectTasksService.updateQsProjectTasks(qsProjectTasks));
    }

    /**
     * 认领项目任务
     */
    @Log(title = "项目任务", businessType = BusinessType.CLAIM)
    @PostMapping("claimAppTasks")
    public AjaxResult claimAppTasks(@RequestBody QsProjectTasks qsProjectTasks) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        return toAjax(qsProjectTasksService.claimQsProjectTasks(qsProjectTasks.getId(), user.getUserId()));
    }

    /**
     * 提报项目任务进度
     */
    @PreAuthorize("@ss.hasPermi('tasks:tasks:report')")
    @Log(title = "项目任务", businessType = BusinessType.REPORT)
    @PostMapping("report")
    public AjaxResult report(@RequestBody QsTasksProgress qsTasksProgress) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        qsTasksProgress.setClaimerId(user.getUserId());
        return toAjax(qsProjectTasksService.reportQsTasksProgress(qsTasksProgress));
    }

    /**
     * 提报项目任务进度
     */
    @Log(title = "项目任务", businessType = BusinessType.REPORT)
    @PostMapping("reportAppTasksProgress")
    public AjaxResult reportAppTasksProgress(@RequestBody QsTasksProgress qsTasksProgress) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        qsTasksProgress.setClaimerId(user.getUserId());
        return toAjax(qsProjectTasksService.reportQsTasksProgress(qsTasksProgress));
    }
}
